<template>
  <a-modal
    title="新建/修改"
    :width="640"
    :visible="visible"
    :confirmLoading="loading"
    @ok="() => { $emit('ok') }"
    @cancel="() => { $emit('cancel') }"
  >
    <a-spin :spinning="loading">
      <a-form :form="form" v-bind="formLayout">
        <!-- 检查是否有 id 并且大于0，大于0是修改。其他是新增，新增不显示主键ID -->
        <a-form-item v-show="model && model.id > 0" label="主键ID">
          <a-input v-decorator="['id', { initialValue: 0 }]" disabled />
        </a-form-item>
        <a-form-item label="名字">
          <a-input v-model="model.name" v-decorator="['name', {rules: [{required: true, min: 2,max:100, message: '请输入至少2个至多100个字符名字！'}]}]" />
        </a-form-item>
        <a-form-item label="描述">
          <a-textarea v-model="model.description" v-decorator="['description', {rules: [{required: true, min: 5,max:500, message: '请输入至少5个至多500个字符的内容描述！'}]}]" :auto-size="{ minRows: 4, maxRows: 6 }" />
        </a-form-item>
        <a-form-item label="图标">
          <a-upload
                  :action="uploadUrl"
                  list-type="picture-card"
                  :file-list="uploadFileList"
                  multiple = "true"
                  :beforeUpload="uploadBefore"
                  @preview="uploadHandlePreview"
                  @change="uploadHandleChange"
          >
            <div v-if="uploadFileList.length < 4">
              <a-icon type="plus" />
              <div class="ant-upload-text">
                上传（为了微信端美观，请上传四张图）
              </div>
            </div>
          </a-upload>
          <a-modal :visible="uploadPreviewVisible" :footer="null" @cancel="uploadHandleCancel">
            <img alt="example" style="width: 100%" :src="uploadPreviewImage" />
          </a-modal>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'

// 表单字段
const fields = ['description', 'id', 'name', 'icon']
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    }
  },
  data () {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      }
    }
    return {
      uploadPreviewVisible: false,
      uploadPreviewImage: '',
      uploadUrl: window.baseUrl + '/tools/file/upload' + window.backPrefix,
      uploadFileList: [], // uid: '-1',name: 'image.png',status: 'done',url:http://
      form: this.$form.createForm(this),
    }
  },
  created () {
    // 防止表单未注册
    fields.forEach(v => this.form.getFieldDecorator(v))

    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
      // 处理图片
      this.changeIconToLocalFile(this.model.icon)
      this.model && this.form.setFieldsValue(pick(this.model, fields))
    })
  },
  methods: {
    uploadBefore() { // 长传之前
      if (this.uploadFileList.length >= 4 ) {
        this.$message.error('最多只能上传四张图片')
      }
    },
    changeLocalFileToIcon(fileList) { // 将数组转化为 数据库容易保存的icon字符串
      this.model.icon = ''
      const tempPath = [];
      for (let i = 0; i < fileList.length; i++ ) {
        if (fileList[i].url != undefined) {
          tempPath.push(fileList[i].url);
        }else{
          if (fileList[i].response.code > 0) {
            tempPath.push(fileList[i].response.data.remote_path);
          }
        }
      }
      this.model.icon = JSON.stringify(tempPath);
    },
    changeIconToLocalFile(iconsStr) { // 将icon字符串转化为 框架能够识别的 数组
      this.uploadFileList = []
      const icons = JSON.parse(iconsStr)
      for (const icon in icons) {
        const temp = {
          uid: icon, name: icons[icon], status: 'done', url: icons[icon]
        }
        this.uploadFileList.push(temp)
      }
    },
    uploadHandleCancel() {
      this.uploadPreviewVisible = false;
    },
    async uploadHandlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.uploadPreviewImage = file.url || file.preview;
      this.uploadPreviewVisible = true;
    },
    uploadHandleChange({ fileList }) {
      this.uploadFileList = fileList;
      this.changeLocalFileToIcon(fileList)
    },
  },
}
</script>
<style>
  /* you can make up upload button and sample style by using stylesheets */
  .ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }
</style>
